<template>
  <div>
    <Modal
      v-model="isShowModal"
      :title="title"
      @on-cancel="hide('formValidate')"
      :mask-closable="false"
      width="80vw"
    >
      <Form
        ref="formValidate"
        :model="params"
        :rules="ruleValidate"
        label-position="top"
      >
        <div class="form-item-title">
          基本信息
        </div>
        <Row :gutter="16">
          <Col :span="12">
            <FormItem label="门店名称：" prop="name">
              <Input v-model.trim="params.name" placeholder="门店名称"></Input>
            </FormItem>
          </Col>
          <Col :span="12">
            <FormItem label="省市区：" prop="area">
              <Row :gutter="5">
                <Col :span="8">
                  <Select
                    v-model="params.province"
                    style=""
                    placeholder="选择省"
                  >
                    <Option
                      v-for="item in regionDataList"
                      :value="item.label"
                      :key="item.label"
                    >
                      {{ item.label }}
                    </Option>
                  </Select>
                </Col>
                <Col :span="8">
                  <Select v-model="params.city" style="" placeholder="选择市">
                    <Option
                      v-for="item in regionDataList2"
                      :value="item.label"
                      :key="item.label"
                    >
                      {{ item.label }}
                    </Option>
                  </Select>
                </Col>
                <Col :span="8">
                  <Select v-model="params.district" style="" placeholder="选择区">
                    <Option
                      v-for="item in regionDataList3"
                      :value="item.label"
                      :key="item.label"
                    >
                      {{ item.label }}
                    </Option>
                  </Select>
                </Col>
              </Row>
            </FormItem>
          </Col>

          <Col :span="6">
            <FormItem label="详细地址：" prop="address">
              <Input
                v-model.trim="params.address"
                placeholder="详细地址"
              ></Input>
            </FormItem>
          </Col>
          <Col :span="6">
            <FormItem label="经营者姓名：" prop="managerName">
              <Input
                v-model.trim="params.managerName"
                placeholder="经营者姓名"
              ></Input>
            </FormItem>
          </Col>
          <Col :span="6">
            <FormItem label="经营者联系方式：" prop="managerPhone">
              <Input
                v-model.trim="params.managerPhone"
                placeholder="经营者联系方式"
              ></Input>
            </FormItem>
          </Col>
          <Col :span="6">
            <FormItem label="podId:" prop="dyPoiId">
              <Input
                v-model.trim="params.dyPoiId"
                placeholder="podId"
              ></Input>
            </FormItem>
          </Col>
        </Row>
        <div class="form-item-title">
          运营信息
        </div>
        <Row :gutter="16">
          <Col :span="12">
            <FormItem label="所属运营：" prop="operation">
              <Input
                v-model.trim="params.operation"
                placeholder="所属运营"
              ></Input>
            </FormItem>
          </Col>
          <Col :span="12">
            <FormItem label="群聊名称：" prop="groupChat">
              <Input
                v-model.trim="params.groupChat"
                placeholder="群聊名称"
              ></Input>
            </FormItem>
          </Col>
        </Row>
        <div class="form-item-title">
          合作信息
        </div>
        <Row :gutter="16">
          <Col :span="6">
            <FormItem label="合作时间：" prop="cooperateStartTime">
              <DatePicker
                v-model="params.cooperateStartTime"
                type="date"
                placeholder="合作时间"
                style="width: 100%;"
              ></DatePicker>
            </FormItem>
          </Col>
          <Col :span="6">
            <FormItem label="营业状态：" prop="state">
              <Select clearable v-model="params.state" placeholder="营业状态">
                <Option :value="0">未营业</Option>
                <Option :value="1">营业中</Option>
              </Select>
            </FormItem>
          </Col>
          <Col :span="6">
            <FormItem label="解约时间：" prop="cooperateEndTime">
              <DatePicker
                v-model="params.cooperateEndTime"
                type="date"
                placeholder="解约时间"
                style="width: 100%;"
              ></DatePicker>
            </FormItem>
          </Col>
          <Col :span="6">
            <FormItem label="解约原因：" prop="cooperateEndRemark">
              <Input
                v-model.trim="params.cooperateEndRemark"
                placeholder="解约原因"
              ></Input>
            </FormItem>
          </Col>
          <Col :span="6">
            <FormItem label="门店结算人姓名：" prop="settlementUser">
              <Input
                v-model.trim="params.settlementUser"
                placeholder="门店结算人姓名"
              ></Input>
            </FormItem>
          </Col>
          <Col :span="6">
            <FormItem label="门店结算银行卡号：" prop="settlementBankcard">
              <Input
                v-model.trim="params.settlementBankcard"
                placeholder="门店结算银行卡号"
              ></Input>
            </FormItem>
          </Col>
          <Col :span="6">
            <FormItem label="结算卡开户行：" prop="openBack">
              <Input
                v-model.trim="params.openBack"
                placeholder="结算卡开户行"
              ></Input>
            </FormItem>
          </Col>
        </Row>

        <div class="form-item-title">
          资质信息
        </div>
        <Row :gutter="16">
          <Col :span="12">
            <FormItem label="营业执照：" prop="businessLicense">
              <div class="hs-upload-image-box">
                <Upload
                  ref="img1Ref"
                  :action="action"
                  :headers="headers"
                  :show-upload-list="false"
                  name="file"
                  multiple
                  :on-success="uploadImagesSuccess"
                  :default-file-list="defaultFileList"
                >
                  <div class="hs-upload-add">
                    <Icon type="md-add" size="30" />
                  </div>
                </Upload>
                <div
                  class="hs-upload-image"
                  v-for="(item, index) in params.imagesList"
                  :key="item.response.data"
                >
                  <template v-if="item.status == 'finished'">
                    <img :src="item.response.data" />
                    <!--删除图片-->
                    <div
                      class="hs-upload-image-delete"
                      @click="delImage(index)"
                    >
                      <Icon type="md-close" />
                    </div>
                  </template>
                  <template v-else>
                    <Progress
                      v-if="item.showProgress"
                      :percent="item.percentage"
                      hide-info
                    ></Progress>
                  </template>
                </div>
              </div>
            </FormItem>
          </Col>
          <Col :span="12">
            <FormItem label="法人身份证：" prop="idPhoto">
              <div class="hs-upload-image-box">
                <Upload
                  ref="img2Ref"
                  :action="action"
                  :headers="headers"
                  :show-upload-list="false"
                  name="file"
                  multiple
                  :on-success="uploadImagesSuccess2"
                  :default-file-list="defaultFileList2"
                >
                  <div class="hs-upload-add">
                    <Icon type="md-add" size="30" />
                  </div>
                </Upload>
                <div
                  class="hs-upload-image"
                  v-for="(item, index) in params.imagesList2"
                  :key="item.response.data"
                >
                  <template v-if="item.status == 'finished'">
                    <img :src="item.response.data" />
                    <!--删除图片-->
                    <div
                      class="hs-upload-image-delete"
                      @click="delImage2(index)"
                    >
                      <Icon type="md-close" />
                    </div>
                  </template>
                  <template v-else>
                    <Progress
                      v-if="item.showProgress"
                      :percent="item.percentage"
                      hide-info
                    ></Progress>
                  </template>
                </div>
              </div>
            </FormItem>
          </Col>
          <Col :span="6">
            <FormItem label="营业执照名称：" prop="businessLicenseName">
              <Input
                v-model.trim="params.businessLicenseName"
                placeholder="营业执照名称"
              ></Input>
            </FormItem>
          </Col>
          <Col :span="6">
            <FormItem label="法人姓名：" prop="legalPerson">
              <Input
                v-model.trim="params.legalPerson"
                placeholder="法人姓名"
              ></Input>
            </FormItem>
          </Col>
          <Col :span="6">
            <FormItem label="社会统一信用代码：" prop="businessLicenseCode">
              <Input
                v-model.trim="params.businessLicenseCode"
                placeholder="社会统一信用代码"
              ></Input>
            </FormItem>
          </Col>
          <Col :span="6">
            <FormItem label="法人身份证号码：" prop="legalPersonId">
              <Input
                v-model.trim="params.legalPersonId"
                placeholder="法人身份证号码"
              ></Input>
            </FormItem>
          </Col>
        </Row>
        <div class="form-item-title">
          备注
        </div>
        <Row :gutter="16">
          <Col :span="24">
            <FormItem label="备注" prop="remark">
              <Input
                v-model.trim="params.remark"
                placeholder="备注"
                type="textarea"
              ></Input>
            </FormItem>
          </Col>
        </Row>
      </Form>

      <!-- 重写对话框底部按钮 -->
      <div slot="footer">
        <Button @click="hide('formValidate')">取消</Button>
        <Button
          v-if="type != 1"
          type="primary"
          @click="handleSubmit('formValidate')"
          :loading="loadingBtn"
        >
          <span v-if="!loadingBtn">确定</span>
          <span v-else>请稍候...</span>
        </Button>
      </div>
    </Modal>
  </div>
</template>

<script>
  import {
    platformList,
    companyList,
    serviceCodeList
  } from '@/constant/program';
  import moment from 'moment';

  const getDefaultParams = () => {
    return {
      address: '',
      area: '',
      province: '',
      city: '',
      district: '',
      imagesList: [],
      imagesList2: [],
      cooperateEndRemark: '',
      cooperateEndTime: '',
      cooperateStartTime: '',
      groupChat: '',
      managerName: '',
      managerPhone: '',
      name: '',
      operation: '',
      remark: '',
      settlementBankcard: '',
      openBack: '',
      businessLicenseName: '',
      legalPerson: '',
      businessLicenseCode: '',
      legalPersonId: '',
      businessLicense: '',
      idPhoto: '',
      dyPoiId: ''
    };
  };

  export default {
    name: 'program-ope',
    data() {
      return {
        companyList,
        serviceCodeList,
        platformList,
        isShowModal: false,
        loadingBtn: false,
        title: '查看信息',
        type: 0,
        action: this.$uploadURL,
        defaultFileList: [],
        defaultFileList2: [],
        headers: {
          token: JSON.parse(sessionStorage.getItem('J-TOKEN')).token
        },
        params: {
          address: '',
          area: '',
          province: '',
          city: '',
          district: '',
          imagesList: [],
          imagesList2: [],
          cooperateEndRemark: '',
          cooperateEndTime: '',
          cooperateStartTime: '',
          groupChat: '',
          managerName: '',
          managerPhone: '',
          name: '',
          operation: '',
          remark: '',
          settlementBankcard: '',
          openBack: '',
          businessLicenseName: '',
          legalPerson: '',
          businessLicenseCode: '',
          legalPersonId: '',
          businessLicense: '',
          idPhoto: '',
          dyPoiId: ''
        },
        ruleValidate: {}
      };
    },
    computed: {
      regionDataList2() {
        if (this.params.province) {
          const provinceObj = this.regionDataList.find(
            item => item.label == this.params.province
          );
          return provinceObj?.children || [];
        } else {
          return [];
        }
      },
      regionDataList3() {
        if (this.regionDataList2.length == 1) {
          this.params.city = this.regionDataList2[0].label;
        }
        if (this.params.city) {
          const cityObj = this.regionDataList2.find(
            item => item.label == this.params.city
          );
          return cityObj?.children || [];
        }
      }
    },
    methods: {
      delImage(index) {
        const fileList = this.$refs.img1Ref.fileList;
        fileList.splice(index, 1);
        this.params.imagesList = fileList;
      },
      delImage2(index) {
        const fileList = this.$refs.img2Ref.fileList;
        fileList.splice(index, 1);
        this.params.imagesList2 = fileList;
      },
      uploadImagesSuccess(response, file, fileList) {
        if (response.status == 200) {
          this.params.imagesList = [...this.$refs.img1Ref.fileList];
        }
        if (response.status == 201) {
          this.$Message.error(response.msg);
        }
        console.log(fileList);
        if (response.status == 500) {
          this.$Notice.error({
            title: '服务器内部错误',
            desc: '上传图片接口报错',
            duration: 0
          });
        }
      },
      uploadImagesSuccess2(response, file, fileList) {
        if (response.status == 200) {
          this.params.imagesList2 = [...this.$refs.img2Ref.fileList];
        }
        if (response.status == 201) {
          this.$Message.error(response.msg);
        }
        if (response.status == 500) {
          this.$Notice.error({
            title: '服务器内部错误',
            desc: '上传图片接口报错',
            duration: 0
          });
        }
      },
      // 点击提交验证
      handleSubmit(name) {
        // console.log(this.params);
        this.$refs[name].validate(valid => {
          if (valid) {
            // this.$Message.error('验证通过');
            /**
             * type判断
             * 1.查看 2.新增 3.编辑
             */
            switch (this.type) {
              case 1:
                // this.title = '查看分类';
                break;
              case 2:
                // 新增分类
                this.addProgram();
                break;
              case 3:
                // 编辑分类
                this.updateMallGoodsType();
                break;
              default:
                this.$Notice.error({
                  title: '分类管理',
                  desc: '查看，新增，编辑区分判断报错',
                  duration: 0
                });
                break;
            }
          } else {
            this.$Message.error('还有信息没有填写合格哦~');
          }
        });
      },
      // 显示模态框
      show(type, row) {
        this.isShowModal = true;
        this.type = type;
        /**
         * type判断
         * 1.查看 2.新增 3.编辑
         */
        switch (type) {
          case 1:
            this.title = '查看';
            this.queryProgramInfo(row);
            break;
          case 2:
            this.title = '新增';
            this.params = getDefaultParams();
            break;
          case 3:
            this.title = '编辑';
            this.queryProgramInfo(row);
            break;
          default:
            this.$Notice.error({
              title: '分类管理',
              desc: '查看，新增，编辑模态框报错',
              duration: 0
            });
            break;
        }
      },
      // 新增
      addProgram() {
        this.$Spin.show();
        const params = {
          ...this.params,
          businessLicense: this.params.imagesList
            .map(item => item.response.data)
            .join(','),
          idPhoto: this.params.imagesList2.map(item => item.response.data).join(','),
          area: `${this.params.province}${this.params.city}${this.params.district}` || this.params.area,
          cooperateEndTime: moment(this.params.cooperateEndTime).format(
            'YYYY-MM-DD'
          ),
          cooperateStartTime: moment(this.params.cooperateStartTime).format(
            'YYYY-MM-DD'
          )
        };
        this.axios.post('/shopinfo/save', params).then(res => {
          setTimeout(() => {
            this.$Spin.hide();
          }, 300);
          this.$emit('changeData');
          if (res.status == 200) {
            this.$Message.success('操作成功.');
            this.hide('formValidate');
          }
          if (res.status == 201) {
            this.$Message.error(res.msg);
          }
          if (res.status == 500) {
            this.$Notice.error({
              title: '服务器内部错误',
              desc: '新增小程序接口报错',
              duration: 0
            });
          }
        });
      },
      updateMallGoodsType() {
        this.$Spin.show();
        this.axios.post('/shopinfo/update', this.params).then(res => {
          this.$emit('changeData');
          setTimeout(() => {
            this.$Spin.hide();
          }, 300);
          if (res.status == 200) {
            this.$Message.success('操作成功.');
            this.hide('formValidate');
          }
          if (res.status == 201) {
            this.$Message.error(res.msg);
          }
          if (res.status == 500) {
            this.$Notice.error({
              title: '服务器内部错误',
              desc: '编辑小程序接口报错',
              duration: 0
            });
          }
        });
      },
      // 查询分类详情
      queryProgramInfo(row) {
        this.$Spin.show();
        this.axios
          .post('/shopinfo/findInfo', {
            shopinfoId: row.shopinfoId
          })
          .then(res => {
            setTimeout(() => {
              this.$Spin.hide();
            }, 300);
            if (res.status == 200) {
              this.params = {
                ...res.data,
                imagesList: res.data.businessLicense
                  ? res.data.businessLicense.split(',').map(item => {
                      return {
                        response: {
                          data: item
                        },
                        status: 'finished'
                      };
                    })
                  : [],
                imagesList2: res.data.idPhoto
                  ? res.data.idPhoto.split(',').map(item => {
                      return {
                        response: {
                          data: item
                        },
                        status: 'finished'
                      };
                    })
                  : []
              };
            }
            console.log(this.params)
            if (res.status == 500) {
              this.$Notice.error({
                title: '服务器内部错误',
                desc: '查看分类详情接口报错',
                duration: 0
              });
            }
          });
      },

      // 关闭模态框
      hide(name) {
        this.isShowModal = false;
        this.params.goodsMallTypeId = '';

        this.$refs[name].resetFields();
      }
    }
  };
</script>

<style scoped lang="less">
  .form-item-title {
    margin-bottom: 20px;
    font-size: 18px;
    font-weight: 900;
  }
  .hs-upload-image-box {
    display: flex;
    align-items: center;
    position: relative;

    .hs-upload-image {
      width: 85px;
      height: 85px;
      margin-top: 0px;
      margin-left: 10px;
      border: 1px solid #efefef;
      cursor: pointer;
      display: flex;
      align-items: center;
      justify-content: center;
      position: relative;

      .hs-upload-image-delete {
        position: absolute;
        top: -8px;
        right: -8px;
        width: 20px;
        height: 20px;
        background-color: red;
        display: flex;
        align-items: center;
        justify-content: center;
        color: #ffffff;
        border-radius: 50%;
      }

      .hs-upload-image-setting {
        position: absolute;
        bottom: 0;
        width: 100%;
        color: #ffffff;
        height: 40px;
        display: none;
        align-items: center;
        justify-content: center;
        background-color: rgba(0, 0, 0, 0.8);
      }

      img {
        width: 100%;
        height: 100%;
      }
    }

    .hs-upload-add {
      cursor: pointer;
      width: 85px;
      height: 85px;
      display: flex;
      align-items: center;
      justify-content: center;
      border: 1px dashed #cccccc;
      transition: all 0.3s;

      &:hover {
        color: #2d8cf0;
        border: 1px dashed #2d8cf0;
      }
    }
  }
</style>
